<?php

class orderController extends manageController
{

    public function __construct()
    {
        if (!isset($_SESSION['zp_manage']['islogin']) || empty($_SESSION['zp_manage']['islogin'])) {
            Tools::AlertTxt('?md=manage&cl=login&at=login', '请先登录');
            exit;
        }
    }


    public function orderlistAction()
    {
        $table = "orders";
        $func = (!empty($this->params['func'])) ? $this->params['func'] : '';
        $page = (!empty($this->params['page'])) ? (int)$this->params['page'] : 1;

        $order_status = (!empty($this->params['_order_status'])) ? $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int)$this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int)$this->params['_company_no'] : '';         # 分司
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
        $_riders = (!empty($this->params['_riders'])) ? $this->params['_riders'] : '';                          # 骑手电话

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                          # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束
        $startdate1 = $startdate;
        $enddate1 = $enddate;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $sourceS = explode('-', $source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];
        $this->view->setVariable("_riders", $_riders);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("_company_no", $company_no);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("_order_status", ($order_status - 100));
        $this->view->setVariable("_source", $sourceK);
        $this->view->setVariable("sourceN", $sourceN);
        $this->view->setVariable("_shop_no", $shop_no);
        $this->view->setVariable("_express_type", $_express_type);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);

        $store =  $this->GetStores([]);
        $CompanyLiists =  $this->GetCompanys([]);
        $sourceLists =  $this->GetSources([]);
							 
        //抓列表
        $where_fields = 'o.isdeleted = 0 ';
        $where_fields_left = "";// " LEFT JOIN xd_store as c ON o.shop_no = c.store_id ";
        $where_fields_rider_mobile = "";// " LEFT JOIN orders_express as d ON o.id = d.orders_id";

        if (!empty($order_status) && $order_status != '-1') {
            $where_fields .= ' AND o.status=' . ($order_status - 100) . '';
        } else {
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no=' . $shop_no . '';
        }

        if (!empty($_express_type) && $_express_type != 'no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }
        if (!empty($company_no)) {
            $where = array("AND" => array("=" => array('company_id' => $company_no,'isdeleted' => 0)));
            $field = 'id,store_id,storename';
            $_store_list = $this->model->getAll($where, 'xd_store', '', $field);
            $_q_stores=array();
            if(!empty($_store_list)){
                foreach($_store_list as $value){
                    $_q_stores[]=" o.shop_no='".$value['store_id']."' ";
                }
                $where_fields .= " AND (".join(" OR ",$_q_stores) .")";
            }else{
                $where_fields .= " AND o.shop_no='".$company_no."' ";   //没有门店，SQL执行后空值
            }
        }
        if (!empty($_riders)) {
            $where_fields .= " AND d.express_mobile like '%$_riders%'";
        }

        # 开始时间
        if (!empty($startdate) && empty($enddate)) {
            $enddate = date('Y-m-d', strtotime('+30 day', strtotime($startdate)));
        }

        # 结束时间
        if (!empty($enddate) && empty($startdate)) {
            $startdate = date('Y-m-d', strtotime('-30 day', strtotime($enddate)));
        }

        if (!empty($startdate) && !empty($enddate)) {
            $_corderS = $startdate . " 00:00:00";
            $_corderE = $enddate . " 23:59:59";
            $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
        }

        if (empty($startdate) && empty($enddate)) {
            if (!$_order_no && !$_ph_no) {
                $startdate = $enddate = $startdate1 = $enddate1 = date('Y-m-d');
                $_corderS = $startdate . " 00:00:00";
                $_corderE = $enddate . " 23:59:59";
                $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
            }
        }
        $left = "left join orders_express as d ON o.ph_no = d.ph_no and o.status = d.status";
        $sql = "SELECT o.*,d.express_fee ,d.express_order_no,d.shop_express_no FROM orders as o $left  WHERE $where_fields  ORDER BY o.id DESC ";

//         echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $company_id=$store['store_data'][$row['shop_no']]['company_id'];
                $row['name'] = $CompanyLiists[$company_id];
                $rsp_list[] = $row;
            }
        }

        if ($rsp_list) {
            $epress = Data::$_express_type;
            foreach ($rsp_list as &$rspva) {
                foreach ($epress as $exk => $exp) {
                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
                        $rspva['express_type_name'] = $exp;
                    }
                }
            }
        }


        # 订单来源、
        $where_fields_source = array("AND" => array("=" => array('status' => 1, 'isdeleted' => 0)));
        $field_source = 'id,source_name';
        $sourceList = $this->model->getAll($where_fields_source, 'zp_source', '', $field_source);

        foreach ($sourceList as $sourceval) {
            $sourceLists[$sourceval['id']] = $sourceval['source_name'];
        }
        
        $sourceLists =  $this->GetSources([]);
		 
		 
//        echo '<pre>';
//        var_dump($rsp_list);
        $this->view->setVariable("startdate", $startdate1);
        $this->view->setVariable("enddate", $enddate1);
        $this->view->setVariable("CompanyLiists", $CompanyLiists);
        $this->view->setVariable("sourceLists", $sourceLists);
        $this->view->setVariable("storeLiists", $store['storeLiists']);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function orderlist_checkAction()
    {
        $id = empty($this->params["id"]) ? '0' : (int)$this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int)$this->params["page"];
        $OrderData = $this->model->getItemById($id, 'orders');

        //配送记录
        $where = array('AND' => array('=' => array('orders_id' => $id)));
        $orderby = ['id' => 'desc'];
        $orders_express_list = $this->model->getAll($where, 'orders_express', $orderby);
        if ($orders_express_list && count((array)$orders_express_list) > 0) {
            foreach ($orders_express_list as &$r) {
                unset($r['tip']);
                unset($r['tip_remark']);
                $where_tip = array('AND' => array('=' => array('order_no' => $r['shop_express_no'], 'shop_no' => $r['shop_no'], 'status' => 1, 'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where_tip, 'tip_list');
                if ($data) {
                    foreach ($data as $k => $t) {
                        $r['tip'] += $t['price'];
                        $r['tip_remark'] .= isset($t['tip_remark']) ? '备注' . ($k + 1) . ':' . $t['tip_remark'] : '' . ' ';
                    }
                }
            }
        }

        $OrderData['tip'] = $orders_express_list[0]['tip'];
        $OrderData['tip_remark'] = $orders_express_list[0]['tip_remark'];
        $OrderData['shop_express_remark'] = $orders_express_list[0]['shop_express_remark'];
        $OrderData['express'] = $orders_express_list;
        $OrderData['express_fee'] = $orders_express_list[0]['express_fee'];
        $OrderData['express_type'] = $orders_express_list[0]['express_type'];
        $OrderData['express_courier'] = $orders_express_list[0]['express_courier'];
        $OrderData['express_mobile'] = $orders_express_list[0]['express_mobile'];
        $orderProductInfo = $this->model->getItemByOther($where, 'orders_product');
        $OrderData['product'] = $orderProductInfo;
        $epress = Data::$_express_type;
        $_order_status = Data::$_order_status;

        # 门店修改地址
        $where = array('AND' => array('=' => array('orders_id' => $id)));
        $orderby = ['createdt' => 'asc'];
        $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);


        if ($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0) {

            foreach ($shop_delivery_address as $k => $sdd) {
                if ($k == 0) {
                    $shop_delivery_address[$k]['old_receiver_name'] = $OrderData['receiver'];
                    $shop_delivery_address[$k]['old_receiver_tel'] = $OrderData['receiver_tel'];
                    $shop_delivery_address[$k]['old_receiver_address'] = $OrderData['receiver_address'];
                } else {
                    $shop_delivery_address[$k]['old_receiver_name'] = $shop_delivery_address[$k - 1]['receiver_name'];
                    $shop_delivery_address[$k]['old_receiver_tel'] = $shop_delivery_address[$k - 1]['receiver_tel'];
                    $shop_delivery_address[$k]['old_receiver_address'] = $shop_delivery_address[$k - 1]['receiver_address'];
                }
            }
            rsort($shop_delivery_address);
            $OrderData['shop_delivery_address'] = $shop_delivery_address;
            $OrderData['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
            $OrderData['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $OrderData['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $OrderData['distance'] = $shop_delivery_address[0]['distance'];
            $OrderData['lat'] = $shop_delivery_address[0]['lat'];
            $OrderData['lng'] = $shop_delivery_address[0]['lng'];

        }

        $where = array();
        $where['and']['=']['store_id'] = $OrderData['shop_no'];
        $shop_info = $this->model->getItemByOther($where, 'xd_store');
        $shop_info = is_array($shop_info) && count($shop_info) > 0 ? $shop_info[0] : array();
        $this->view->setVariable("shop_info", $shop_info);

        $where = array();
        $where['and']['=']['is_parent'] = 1;
        $company_info = $this->model->getItemByOther($where, 'xd_company');
        if (!empty($company_info)) {
            foreach ($company_info as $key => $value) {
                unset($company_info[$key]);
                $company_info[$value['code']] = $value;
            }
        }
        $this->view->setVariable("company_info", $company_info);

        $this->view->setVariable("page", $page);
        $this->view->setVariable("order_status", $_order_status);
        $this->view->setVariable("express", $epress);
        $this->view->setVariable("rsp_list", $OrderData);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function order_delivery_infoAction()
    {
        $id = empty($this->params["id"]) ? '0' : (int)$this->params["id"];
        $OrderExpressData = $this->model->getItemById($id, 'orders_express');
        $where['and']['=']['shop_express_no'] = $OrderExpressData['shop_express_no'];
        $expressData = $this->model->getItemByOther($where, 'express_data');

        $_express_type = Data::$_express_type;
        $OrderExpressData['express_data'] = $expressData;
        $OrderExpressData['express_type_data'] = $_express_type;
        echo json_encode($OrderExpressData);
    }


    /**
     * 异常订单
     */
    public function orderErrorListAction()
    {
        $page = (!empty($this->params['page'])) ? (int)$this->params['page'] : 1;
        $order_status = (!empty($this->params['_eorder_status'])) ? (int)$this->params['_eorder_status'] : '';         # 订单状态
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                           # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                  # 订单号
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;
        $this->view->setVariable("number_page", $number_page);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("_eorder_status", $order_status);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);

        //抓列表
        $where = 'o.isdeleted = 0  AND ';
        if (!empty($_ph_no)) {
            $where .= 'op.ph_no="' . $_ph_no . '" AND';
        }

        if (!empty($_order_no)) {
            $where .= 'op.order_no="' . $_order_no . '" AND';
        }

        if (!empty($order_status)) {
            $where .= 'o.status=' . $order_status . '  AND ';
        } else {
            $where .= '(o.status=6 OR o.status=7)  AND ';
        }
        $where .= ' op.express_type = "self" ';
        $sql = "SELECT op.ph_no,op.push_response_data,op.status,op.express_type,op.id,op.shop_no,op.order_no,o.source,s.storename as shop_name FROM orders as o left join xd_store as s ON s.store_id = o.shop_no left join orders_express as op ON o.ph_no = op.ph_no WHERE $where ";

//        echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["QUERY_STRING"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    public function orderErrorList_checkAction()
    {
        $id = empty($this->params["id"]) ? '0' : (int)$this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int)$this->params["page"];

        $exp_where = array();
        $exp_where['AND']['=']['id'] = $id;
        $OrderExpressData = $this->model->getItemByOther($exp_where, 'orders_express');

        if ($OrderExpressData && count((array)$OrderExpressData) > 0) {
            foreach ($OrderExpressData as &$r) {
                unset($r['tip']);
                unset($r['tip_remark']);
                $where_tip = array('AND' => array('=' => array('order_no' => $r['shop_express_no'], 'shop_no' => $r['shop_no'], 'status' => 1, 'isdeleted' => 0)));
                $data = $this->model->getItemByOther($where_tip, 'tip_list');
                if ($data) {
                    foreach ($data as $k => $t) {
                        $r['tip'] += $t['price'];
                        $r['tip_remark'] .= isset($t['tip_remark']) ? '备注' . ($k + 1) . ':' . $t['tip_remark'] : '' . ' ';
                    }
                }
            }
        }
        $where = array();
        $where['AND']['=']['id'] = $OrderExpressData[0]['orders_id'];
        $OrderDatas = $this->model->getItemByOther($where, 'orders');
        $OrderData = $OrderDatas[0];
        $OrderData['tip'] = $OrderExpressData[0]['tip'];
        $OrderData['tip_remark'] = $OrderExpressData[0]['tip_remark'];
        $OrderData['shop_express_remark'] = $OrderExpressData[0]['shop_express_remark'];
        $OrderData['express'] = $OrderExpressData;
        $where = array();
        $where['and']['=']['orders_id'] = $OrderData['id'];
        $orderProductInfo = $this->model->getItemByOther($where, 'orders_product');
        $OrderData['product'] = $orderProductInfo;

        # 门店修改地址
        $where = array('AND' => array('=' => array('orders_id' => $id)));
        $orderby = ['createdt' => 'desc'];
        $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);

        if ($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0) {
            $OrderData['shop_delivery_address'] = $shop_delivery_address;
            $OrderData['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $OrderData['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $OrderData['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
        }

        $this->view->setVariable("page", $page);
        $this->view->setVariable("rsp_list", $OrderData);

        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    public function orderErrorList_check1Action()
    {
        $id = empty($this->params["id"]) ? '0' : (int)$this->params["id"];
        $page = empty($this->params["page"]) ? '0' : (int)$this->params["page"];
        $OrderData = $this->model->getItemById($id, 'orders');
        $where['and']['=']['orders_id'] = $OrderData['id'];
        $orderInfo = $this->model->getItemByOther($where, 'orders_express');
        $OrderData['express'] = $orderInfo;
        $orderProductInfo = $this->model->getItemByOther($where, 'orders_product');
        $OrderData['product'] = $orderProductInfo;

        $epress = Data::$_express_type;
        $_order_status = Data::$_order_status;
        $this->view->setVariable("page", $page);
        $this->view->setVariable("order_status", $_order_status);
        $this->view->setVariable("express", $epress);
        $this->view->setVariable("rsp_list", $OrderData);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }

    /**
     * 异常导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */
    public function Error_exportAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $order_status = (!empty($this->params['_order_status'])) ? $this->params['_order_status'] : 0;         # 订单状态
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
        if (!empty($_ph_no)) {
            $ph_no = 'op.ph_no="' . $_ph_no . '" AND';
        }

        if (!empty($_order_no)) {
            $order_no = 'op.order_no="' . $_order_no . '" AND';
        }

        if (!empty($order_status)) {
            $status = 'o.status=' . $order_status;
        } else {
            $status = '(o.status=6 OR o.status = 7) ';
        }
        $where = 'op.isdeleted=0 AND ' . $ph_no . ' ' . $order_no . ' ' . $status . ' AND op.express_type = "self"  group by op.id order by op.updatedt desc';
        $Joinprders = "left join orders  as o ON o.id = op.orders_id";
        $JoinStore = "left join xd_store  as s ON s.store_id = op.shop_no";
        $sql = "SELECT op.shop_delivery_address, op.ph_no,op.push_response_data,op.status,op.express_type,op.shop_express_no,op.shop_delivery_time,op.shop_pickup_time,op.shop_goods_weight,op.express_courier,op.express_mobile,op.express_order_no,o.*  FROM orders_express as op $Joinprders $JoinStore WHERE $where";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if ($rsp_list) {
            # 订单商品清单
            foreach ($rsp_list as &$o) {
                $where = ['AND' => ['=' => ['orders_id' => $o['id']]]];
                $o['product'] = $this->model->getItemByOther($where, 'orders_product');

            }

            # 组装合并
            $NewRspList = [];
            foreach ($rsp_list as $rsp) {
                if ($rsp['product']) {
                    foreach ($rsp['product'] as $p) {
                        unset($p['status']);
                        unset($p['order_no']);
                        unset($rsp['product']);
                        $NewRspList[] = array_merge($rsp, $p);
                    }
                } else {
                    $NewRspList[] = $rsp;
                }
            }
            $epress = Data::$_express_type;
            foreach ($NewRspList as &$rspva) {
                foreach ($epress as $exk => $exp) {
                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
                        $rspva['express_type_name'] = $exp;
                    }
                }
            }
        }

        if ($NewRspList && is_array($NewRspList) && count($NewRspList) > 0) {
            $titles = array('序号', '订单编号', '订单来源', '订单清单', '数量', '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人', '收货地址', '派单单号',
                '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态', '操作时间','POS生成订单');
            $tableName = "订单列表";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles) . "\n";
            foreach ($NewRspList as $key => $row) {
                $seller_remarks = $id = preg_replace("/(\n)|(\t)|(,)|(，)/", '!', $row['seller_remarks']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['qty'] = $row['qty'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $row['customre_memo'];
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                if ($row['shop_delivery_address']) {
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                } else {
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = Data::$_express_status[$row['status']];
                $exportIinfo['createdt'] = $row['createdt'];
                $exportIinfo['pos_no'] = $row['order_no'];
                echo implode("\t ,", $exportIinfo) . "\n";
            }

//        die;
            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            ob_end_flush();
            exit;
        } else {
            Tools::AlertTxt('?md=manage&cl=order&at=orderErrorList', '没有可汇出数据');
            exit;
        }

    }

    public function export_xlsAction()
    {
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $flag = (!empty($this->params['flag'])) ? $this->params['flag'] : '';
        $qplatform = (!empty($this->params['qplatform'])) ? (int)$this->params['qplatform'] : 1;
        $startdt = (!empty($this->params['startdt'])) ? $this->params['startdt'] : '';
        $enddt = (!empty($this->params['enddt'])) ? $this->params['enddt'] : '';

        $startdt = empty($startdt) ? date("Y-m-d", strtotime("-30 days")) : $startdt;
        $enddt = empty($enddt) ? date("Y-m-d") : $enddt;

        /*
                $order_status = (!empty($this->params['_order_status'])) ?  $this->params['_order_status'] : 0;         # 订单状态
                $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
                $shop_no = (!empty($this->params['_shop_no'])) ? (int) $this->params['_shop_no'] : '';                  # 配送门店
                $company_no = (!empty($this->params['_company_no'])) ? (int) $this->params['_company_no'] : '';         # 分司
                $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
                $_ph_no = (!empty($this->params['_ph_no'])) ?  $this->params['_ph_no'] : '';                            # 配货号
                $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
                $_corder = (!empty($this->params['_corder'])) ? $this->params['_corder'] : '';                          # 下单时间
                $sourceS = explode('-',$source);
                $sourceN = $sourceS[0];
                $sourceK = $sourceS[1];

                $order_status += 100;

                $where_fields = 'o.isdeleted = 0 ';

                if (!empty($order_status)  && $order_status != '-1') {
                    $where_fields .= ' AND o.status='.($order_status-100).'';
                }else{
                    $where_fields .= ' AND o.status < 6';
                }
                if (!empty($shop_no)) {
                    $where_fields .= ' AND o.shop_no='.$shop_no.'';
                }

                if (!empty($_express_type) && $_express_type !='no') {
                    $where_fields .= " AND o.express_type='$_express_type'";
                }
                if (!empty($_ph_no)) {
                    $where_fields .= " AND o.ph_no='$_ph_no'";
                }
                if (!empty($_order_no)) {
                    $where_fields .= " AND o.order_no='$_order_no'";
                }
                if (!empty($source)) {
                    $where_fields .= " AND o.source = '$sourceN'";
                }
                if (!empty($company_no)) {
                    $where_fields .= " AND b.code = $company_no";
                }
                if (!empty($_corder)) {
                    $_corderS = $_corder." 00:00:00";
                    $_corderE = $_corder." 23:59:59";
                    $where_fields .= " AND o.order_time > '$_corderS' AND o.order_time < '$_corderE'";
                }

                $JoinStore = "left join xd_store  as s ON s.store_id = o.shop_no";
                $sql = "SELECT s.longitude,s.latitude,exp.express_fee,exp.push_response_data,exp.order_no,exp.ph_no,exp.push_response_data,exp.status,exp.express_type,
        exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time,exp.shop_goods_weight,exp.express_courier,exp.express_mobile,
        exp.express_order_no,exp.shop_delivery_address,o.*  FROM orders as o
        LEFT JOIN ( SELECT  max(id) id, ph_no FROM orders_express GROUP BY ph_no ) as temp ON o.ph_no = temp.ph_no
        LEFT JOIN orders_express as exp ON exp.id = temp.id
         $JoinStore
        WHERE $where_fields ";

                //echo $sql;exit;

                $res = $this->model->getAny($sql);
                if (!empty($res)) {
                    while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                        $rsp_list[] = $row;
                    }
                }

                $NewRspList = array();

                if($rsp_list){
                    # 订单商品清单
                    foreach($rsp_list as &$o){
                        $where = ['AND'=>['='=>['orders_id'=>$o['id']]]];
                        $o['product'] = $this->model->getItemByOther($where,'orders_product');
                    }

                    foreach ($rsp_list as &$rlt){
                        if($rlt['express_type'] == 'self'){
                            if($rlt['shop_delivery_address']){
                                $address = str_replace(' ','',$rlt['shop_delivery_address']);
                            }else{
                                $address = str_replace(' ','',$rlt['receiver_address']);
                            }

                            $data['address'] = $address;
                            $baiduBS = new BaiduLBS();
                            $baiduBSInfo = $baiduBS::getLocation($data);
                            $baiduBSInfoArr = json_decode($baiduBSInfo, true);
                            $BDLongitude= $baiduBSInfoArr['result']['location']['lng'];                # 收件纬度
                            $BDLatitude = $baiduBSInfoArr['result']['location']['lat'];                # 收件经度

                            $distance = $this->getdistanceAction($BDLongitude,$BDLatitude,$rlt['longitude'],$rlt['latitude']);
                            $rlt['distance'] = number_format($distance/1000,2);
                        }elseif($rlt['express_type'] == 'sf'){
                            $exp_res = json_decode($rlt['push_response_data'],true);
                            $rlt['distance'] = isset($exp_res['result'])? $exp_res['result']['delivery_distance_meter']/1000:0;
                        }elseif($rlt['express_type'] == 'ss'){
                            $exp_res = json_decode($rlt['push_response_data'],true);
                            $rlt['distance'] = isset($exp_res['data']) && count($exp_res['data'])>0? $exp_res['data'][0]['distanceTotal']/1000:0;
                        }elseif($rlt['express_type'] == 'dd'){
                            $exp_res = json_decode($rlt['push_response_data'],true);
                            $rlt['distance'] = isset($exp_res['result'])? $exp_res['result']['deliverFee']/1000:0;
                        }
                        $rlt['distance'] = number_format($rlt['distance'],2);
                    }
                    # 组装合并

                    foreach($rsp_list as $rsp){
                        if($rsp['product']){
                            $temp=array();
                            foreach($rsp['product'] as $p){
                                $temp[]=$p['product_name'].'X'.$p['qty'];
                            }
                            $rsp['product_name']=join("; ", $temp);
                        }

                        $NewRspList[] = $rsp;

                    }
                }
                */


        //新建
        //ob_end_clean();
        $eng_title_col = 65;
        $eng_title = 65;
        $resultPHPExcel = new PHPExcel();
        $resultPHPExcel->setActiveSheetIndex(0);
        $objActSheet = $resultPHPExcel->getActiveSheet();
        $objActSheet->setTitle('宅配订单');
        $resultPHPExcel->getActiveSheet()->getColumnDimension(chr($eng_title_col++))->setWidth(5);
        $resultPHPExcel->getActiveSheet()->getColumnDimension(chr($eng_title_col++))->setWidth(15);
        $resultPHPExcel->getActiveSheet()->getColumnDimension(chr($eng_title_col++))->setWidth(15);
        $resultPHPExcel->getActiveSheet()->getColumnDimension(chr($eng_title_col++))->setWidth(15);
        $resultPHPExcel->getActiveSheet()->getColumnDimension(chr($eng_title_col++))->setWidth(15);

        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '序号', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '订单编号', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '订单来源', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '订单清单', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '下单时间', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '生日蜡烛', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '买家备注', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '卖家备注', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '预计提货时间', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '订货人', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '收货人', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '收货地址', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '派单单号', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '配送方式', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '预计送达时间', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '预计取货时间', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '商品重量', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '配送方订单号', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '配送员信息', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '配送状态', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '距离', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '运费', PHPExcel_Cell_DataType::TYPE_STRING);
        $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_title++) . '1', '操作时间', PHPExcel_Cell_DataType::TYPE_STRING);

        $eng_cell = 65;
        $i = 2;

        /*
        foreach ($NewRspList as $k => $val) {

            if ($val['shop_delivery_address']) {
                $receiver_address = $val['shop_delivery_address'];
            } else {
                $receiver_address = $val['receiver_address'];
            }

            if ($val['express_courier']) {
                $express_mobile = $val['express_mobile'];
                $express_courier = $val['express_courier'] . "($express_mobile)";
            } else {
                $express_courier = '';
            }

            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, ($k+1), PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['order_no'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['source'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['product_name'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['order_time'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['birthday_candles'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['customre_memo'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['seller_remarks'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['delivery_time'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValueExplicit(chr($eng_cell++) . $i, $val['buyer'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['receiver'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $receiver_address, PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['shop_express_no'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, Data::$_express_type[$val['express_type']], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['shop_delivery_time'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['shop_pickup_time'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['shop_goods_weight'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValueExplicit(chr($eng_cell++) . $i, $val['express_order_no'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $express_courier, PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i,  Data::$_express_status[$val['status']], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['distance'].'千米', PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['express_fee'], PHPExcel_Cell_DataType::TYPE_STRING);
            $resultPHPExcel->getActiveSheet()->setCellValue(chr($eng_cell++) . $i, $val['createdt'], PHPExcel_Cell_DataType::TYPE_STRING);

            $i++;
            $eng_cell = 65;
        }
*/

        $name = date("YmdHis", time());
        $outputFileName = "orderlist_$name.xlsx";

        //日志
        $log = array();
        $log['table_id'] = 0;
        $log['table_name'] = "ordersProduct";
        $log['type'] = 5;
        $log['page'] = "订单列表";
        $log['content'] = $log['page'] . "：" . $name . ".xlsx";
        $org = array();
        $modify = array();
        $this->model->setLog($log, $org, $modify);

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $outputFileName . '"');
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($resultPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }


    /**
     * 导出
     * @param $vars
     * @param $temp_code
     * @throws Exception
     */

    public function exportAction()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');

        $order_status = (!empty($this->params['_order_status'])) ? $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int)$this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int)$this->params['_company_no'] : '';         # 分司
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                          # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束


        # 获取门店列表
        $where_fields = array("AND" => array("=" => array('isdeleted' => 0)));
        $field = 'id,store_id,storename,company_id';
        $storeLiist = $this->model->getAll($where_fields, 'xd_store', '', $field);
        $store_data=array();
        # 重构
        foreach ($storeLiist as $stoval) {
            $storeLiists[$stoval['store_id']] = $stoval['storename'];
            $store_data[$stoval['store_id']] =$stoval;
        }

        # 获取分司列表
        $where_fields_c = array("AND" => array("=" => array('is_parent' => 1, 'isdeleted' => 0)));
        $field_c = 'id,code,name';
        $CompanyLiist = $this->model->getAll($where_fields_c, 'xd_company', '', $field_c);

        # 重构
        foreach ($CompanyLiist as $cval) {
            $CompanyLiists[$cval['code']] = $cval['name'];
        }

        $order_status += 100;

        $where_fields = 'o.isdeleted = 0 ';

        if (!empty($order_status) && $order_status != '-1') {
            $where_fields .= ' AND o.status=' . ($order_status - 100) . '';
        } else {
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no=' . $shop_no . '';
        }

        if (!empty($_express_type) && $_express_type != 'no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$source'";
        }
        if (!empty($company_no)) {
            $where = array("AND" => array("=" => array('company_id' => $company_no,'isdeleted' => 0)));
            $field = 'id,store_id,storename';
            $_store_list = $this->model->getAll($where, 'xd_store', '', $field);
            $_q_stores=array();
            if(!empty($_store_list)){
                foreach($_store_list as $value){
                    $_q_stores[]=" o.shop_no='".$value['store_id']."' ";
                }
                $where_fields .= " AND (".join(" OR ",$_q_stores) .")";
            }else{
                $where_fields .= " AND o.shop_no='".$company_no."' ";   //没有门店，SQL执行后空值
            }
        }


        # 开始时间
        if (!empty($startdate) && empty($enddate)) {
            $enddate = date('Y-m-d', strtotime('+30 day', strtotime($startdate)));
        }


        # 结束时间
        if (!empty($enddate) && empty($startdate)) {
            $startdate = date('Y-m-d', strtotime('-30 day', strtotime($enddate)));
        }

        if (!empty($startdate) && !empty($enddate)) {
            $_corderS = $startdate . " 00:00:00";
            $_corderE = $enddate . " 23:59:59";
            $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
        }
        if (empty($startdate) && empty($enddate)) {
            if (!$_order_no && !$_ph_no) {
                $startdate = $enddate = date('Y-m-d');
                $_corderS = $startdate . " 00:00:00";
                $_corderE = $enddate . " 23:59:59";
                $where_fields .= " AND o.order_time >= '$_corderS' AND o.order_time <= '$_corderE'";
            }
        }

        $total_count = 0;
        $sql = "SELECT count(o.id) as count  FROM orders as o   WHERE $where_fields ";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $total_count = $row['count'];
            }
        }

        if ($total_count <= 0) {
            Tools::AlertTxt('?md=manage&cl=order&at=orderlist', '没有可汇出数据');

            exit;
        }
        $rsp_list = array();
        $number_page = 500;
        $total_page = floor($total_count / $number_page) + 1;

        for ($page = 1; $page <= $total_page; $page++) {


            $sql = "SELECT exp.express_fee,exp.push_response_data,exp.order_no,exp.ph_no,exp.push_response_data,exp.status,exp.express_type,
exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time,exp.shop_goods_weight,exp.express_courier,exp.express_mobile,exp.tip,exp.tip_remark,exp.shop_express_remark,
exp.express_order_no,exp.shop_delivery_address, op.product_name, o.* FROM orders as o 
LEFT JOIN ( SELECT  max(id) id, ph_no FROM orders_express GROUP BY ph_no ) as temp ON o.ph_no = temp.ph_no 
LEFT JOIN orders_express as exp ON exp.id = temp.id  
LEFT JOIN (SELECT orders_id,group_concat(concat(product_name,'X',qty)) as product_name FROM orders_product GROUP BY orders_id) as op ON op.orders_id = o.id
WHERE $where_fields ";


            $sql =" SELECT o.* FROM  orders as o WHERE $where_fields ";
            $offset = ($page - 1) * $number_page;
            $limit = ' LIMIT  ' . $offset . ', ' . $number_page . ' ';
            $sql .= $limit;

            //echo $sql;exit;

            $res = $this->model->getAny($sql);
            if (!empty($res)) {
                while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                    $company_id=$store_data[$row['shop_no']]['company_id'];
                    $row['company_name'] = $CompanyLiists[$company_id];
                    $row['latitude'] =$store_data[$row['shop_no']]['latitude'];
                    $row['longitude'] =$store_data[$row['shop_no']]['longitude'];
                    $row['storename'] =$store_data[$row['shop_no']]['storename'];
                    $rsp_list[] = $row;
                }
                foreach($rsp_list as $key=>$value){
                    $sql =" SELECT exp.express_fee,exp.push_response_data,exp.order_no,exp.ph_no,exp.push_response_data,exp.status,exp.express_type,
exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time,exp.shop_goods_weight,exp.express_courier,exp.express_mobile,exp.tip,exp.tip_remark,exp.shop_express_remark,
exp.express_order_no,exp.shop_delivery_address FROM  orders_express as exp WHERE exp.ph_no='".$value['ph_no']."' ORDER BY exp.id LIMIT 0,1 ";
                    $res = $this->model->getAny($sql);
                    if (!empty($res)) {
                        while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                            $value=array_merge($value,$row);
                        }
                    }
                    $rsp_list[$key]=$value;
                }

                foreach($rsp_list as $key=>$value){
                    $sql =" SELECT orders_id,group_concat(concat(product_name,'X',qty)) as product_name FROM orders_product WHERE orders_id='".$value['id']."' GROUP BY orders_id ";
                    $res = $this->model->getAny($sql);
                    if (!empty($res)) {
                        while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                            $value['product_name']=$row['product_name'];
                        }
                    }
                    $rsp_list[$key]=$value;
                }

                foreach($rsp_list as $key=>$value){
                    $sql =" SELECT id FROM shop_delivery_address WHERE orders_id='".$value['id']."' LIMIT 0,1  ";
                    $res = $this->model->getAny($sql);
                    if (!empty($res)) {
                        while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                            $value['has_modify_addr']=1;
                        }
                    }
                    $rsp_list[$key]=$value;
                }


            }
        }

        if ($rsp_list && is_array($rsp_list) && count($rsp_list) > 0) {
            foreach ($rsp_list as &$rlt) {
                $distance = $rlt['distance'];
                $exp_res = json_decode($rlt['push_response_data'], true);

                if ($rlt['express_type'] == 'self') {
                    $distance = $rlt['distance'];
                } elseif ($rlt['express_type'] == 'sf') {
                    $distance = isset($exp_res['result']) ? $exp_res['result']['delivery_distance_meter'] : $rlt['distance'];
                } elseif ($rlt['express_type'] == 'ss') {
                    $distance = isset($exp_res['data']) && count($exp_res['data']) > 0 ? $exp_res['data'][0]['distanceTotal'] : $rlt['distance'];
                } elseif ($rlt['express_type'] == 'dd') {
                    $distance = isset($exp_res['result']) ? $exp_res['result']['distance'] : $rlt['distance'];
                }elseif ($rlt['express_type'] == 'jrd') {

                    $distance = isset($exp_res['result']) ? $exp_res['result']['address_distance'] : $rlt['distance'];

                }
                if($rlt['express_type'] != 'jrd'){
                    $rlt['distance'] = round($distance / 1000, 2);
                }else{
                    $rlt['distance'] = $distance;
                }
            }

            $titles = array('序号', '门店名称', '订单编号', '订单来源', '订单清单', '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人','收货人手机号', '收货地址', '派单单号',
                '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态', '实际距离(单位:km)', '运费', '小费', '渠道运费', '小费备注', '指派备注', '分司名称', '操作时间','POS生成订单','是否有修改收货信息');
            $tableName = "订单列表_" . date('YmdHis');
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles) . "\n";
            foreach ($rsp_list as $key => $row) {
                $seller_remarks = Tools::clearSymbolForCSV($row['seller_remarks']);
                $customre_memo = Tools::clearSymbolForCSV($row['customre_memo']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['storename'] = $row['storename'];
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                //$exportIinfo['qty'] = $row['qty'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $customre_memo;
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                $exportIinfo['receiver_tel'] = $row['receiver_tel'];
                if ($row['shop_delivery_address']) {
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                } else {
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = empty($row['status']) ? '' : Data::$_express_status[$row['status']];
                $exportIinfo['distance'] = ($row['distance']>0)?$row['distance'].'千米':'';
                $exportIinfo['express_fee'] = $row['express_fee'];
                $exportIinfo['tip'] = $row['tip'];
                $exportIinfo['pos_fee'] = $row['pos_fee'] > 0 ? $row['pos_fee'] : 0;
                $exportIinfo['tip_remark'] = $row['tip_remark'];
                $exportIinfo['shop_express_remark'] = $row['shop_express_remark'];
                $exportIinfo['company_name'] = $row['company_name'];
                $exportIinfo['createdt'] = $row['createdt'];
                $exportIinfo['pos_no'] = $row['order_no'];
                $exportIinfo['has_modify_addr'] = (isset($row['has_modify_addr'])&& $row['has_modify_addr']==1)?'有':'';
                foreach ($exportIinfo as $k => $v) {
                    $v = Tools::clearSymbolForCSV($v);
                    $exportIinfo[$k] = $v;
                }

                echo implode("\t ,", $exportIinfo) . "\n";
            }
            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            ob_end_flush();
            exit;

        }else {
            Tools::AlertTxt('?md=manage&cl=order&at=orderlist', '没有可汇出数据');

            exit;
        }
    }


    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    private function getdistanceAction($lng1, $lat1, $lng2, $lat2)
    {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }

    public function export111Action()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1280M');
        require_once("plugin/PHPExcel.php");
        require_once('plugin/PHPExcel/IOFactory.php');
        require_once('plugin/PHPExcel/Writer/Excel5.php');
        require_once('plugin/PHPExcel/Writer/Excel2007.php');
        $order_status = (!empty($this->params['_order_status'])) ? $this->params['_order_status'] : 0;         # 订单状态
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int)$this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int)$this->params['_company_no'] : '';         # 分司
        $_express_type = (!empty($this->params['_express_type'])) ? $this->params['_express_type'] : '';        # 配送方式
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号
        $_corder = (!empty($this->params['_corder'])) ? $this->params['_corder'] : '';                          # 下单时间
        $sourceS = explode('-', $source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];

        $order_status += 100;
        //抓列表
        $where_fields = 'o.isdeleted = 0 ';

        if (!empty($order_status) && $order_status != '-1') {
            $where_fields .= ' AND o.status=' . ($order_status - 100) . '';
        } else {
            $where_fields .= ' AND o.status < 6';
        }
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no=' . $shop_no . '';
        }

        if (!empty($_express_type) && $_express_type != 'no') {
            $where_fields .= " AND o.express_type='$_express_type'";
        }
        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }
        if (!empty($company_no)) {
            $where_fields .= " AND b.code = $company_no";
        }
        if (!empty($_corder)) {
            $_corderS = $_corder . " 00:00:00";
            $_corderE = $_corder . " 23:59:59";
            $where_fields .= " AND o.order_time > '$_corderS' AND o.order_time < '$_corderE'";
        }
        $sql = "SELECT  o.*,exp.shop_delivery_address,exp.express_courier,exp.express_mobile,exp.shop_express_no,exp.shop_delivery_time,exp.shop_pickup_time ,exp.shop_goods_weight,exp.express_order_no,b.name FROM orders as o 
        left join xd_store as s ON o.shop_no = s.store_id 
        left join xd_company as b ON s.company_id = b.code 
        left join (SELECT orders_id,shop_delivery_address,express_courier,express_mobile,ph_no,shop_express_no,shop_delivery_time,shop_pickup_time,shop_goods_weight,express_order_no FROM orders_express  where status < 6 ) as exp
        ON o.id = exp.orders_id where  $where_fields GROUP BY o.id";

        $res = $this->model->getAny($sql);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $rsp_list[] = $row;
            }
        }
        if ($rsp_list) {
            # 订单商品清单
            foreach ($rsp_list as &$o) {
                $where = ['AND' => ['=' => ['orders_id' => $o['id']]]];
                $o['product'] = $this->model->getItemByOther($where, 'orders_product');

            }
            $NewRspList = [];
            foreach ($rsp_list as $rsp) {
                if ($rsp['product']) {
                    foreach ($rsp['product'] as $p) {
                        unset($p['status']);
                        unset($p['order_no']);
                        unset($rsp['product']);
                        $NewRspList[] = array_merge($rsp, $p);
                    }
                } else {
                    $NewRspList[] = $rsp;
                }
            }

//            $epress = Data::$_express_type;
//            foreach ($NewRspList as &$rspva) {
//                foreach ($epress as $exk => $exp) {
//                    if ($rspva["express_type"] && $rspva["express_type"] == $exk) {
//                        $rspva['express_type_name'] = $exp;
//                    }
//                }
//            }
        }

        if ($NewRspList && is_array($NewRspList) && count($NewRspList) > 0) {

            $titles = array('序号', '订单编号', '订单来源', '订单清单', '数量', '下单时间', '生日蜡烛', '买家备注', '卖家备注', '预计提货时间', '订货人', '收货人', '收货地址', '派单单号',
                '配送方式', '预计送达时间', '预计取货时间', '商品重量', '配送方订单号', '配送员信息', '配送状态', '距离', '运费', '操作时间');
            $tableName = "订单列表";
            ob_get_clean();
            ob_start();
            echo "\xEF\xBB\xBF";
            echo implode("\t ,", $titles), "\n";
            foreach ($NewRspList as $key => $row) {
                $seller_remarks = $id = preg_replace("/(\n)|(\t)|(,)|(，)/", '!', $row['seller_remarks']);
                $customre_memo = preg_replace("/(\n)|(\t)|(,)|(，)/", '!', $row['customre_memo']);
                if ($row['express_courier']) {
                    $express_mobile = $row['express_mobile'];
                    $express_courier = $row['express_courier'] . "($express_mobile)";
                } else {
                    $express_courier = '';
                }
                $k = $key + 1;
                $exportIinfo['id'] = $k;
                $exportIinfo['order_no'] = $row['order_no'];
                $exportIinfo['source'] = $row['source'];
                $exportIinfo['product_name'] = $row['product_name'];
                $exportIinfo['qty'] = $row['qty'];
                $exportIinfo['order_time'] = $row['order_time'];
                $exportIinfo['birthday_candles'] = $row['birthday_candles'];
                $exportIinfo['customre_memo'] = $customre_memo;
                $exportIinfo['seller_remarks'] = $seller_remarks;
                $exportIinfo['delivery_time'] = $row['delivery_time'];
                $exportIinfo['buyer'] = $row['buyer'];
                $exportIinfo['receiver'] = $row['receiver'];
                if ($row['shop_delivery_address']) {
                    $exportIinfo['receiver_address'] = $row['shop_delivery_address'];
                } else {
                    $exportIinfo['receiver_address'] = $row['receiver_address'];
                }
                $exportIinfo['shop_express_no'] = $row['shop_express_no'];
                $exportIinfo['express_type'] = Data::$_express_type[$row['express_type']];
                $exportIinfo['shop_delivery_time'] = $row['shop_delivery_time'];
                $exportIinfo['shop_pickup_time'] = $row['shop_pickup_time'];
                $exportIinfo['shop_goods_weight'] = $row['shop_goods_weight'];
                $exportIinfo['express_order_no'] = $row['express_order_no'];
                $exportIinfo['express_courier'] = $express_courier;
                $exportIinfo['express_status'] = Data::$_express_status[$row['status']];
                $exportIinfo['distance'] = $row['distance'] . '千米';
                $exportIinfo['express_fee'] = $row['express_fee'];
                $exportIinfo['createdt'] = $row['createdt'];
                echo implode("\t ,", $exportIinfo), "\n";
            }

            header('Content-Disposition: attachment; filename=' . $tableName . ".csv");
            header('Accept-Ranges:bytes');
            header('Content-Length:' . ob_get_length());
            header('Content-Type:text/csv');
            ob_end_flush();

            $log = array();
            $log['table_id'] = 0;
            $log['table_name'] = 'orders';
            $log['type'] = 5;
            $log['page'] = $tableName;
            $log['content'] = $log['page'] . "：" . $tableName . ".csv";
            $org = array();
            $this->model->setLog($log, $org, $exportIinfo);
            exit;
        } else {
            Tools::AlertTxt('?md=manage&cl=order&at=orderlist', '没有可汇出数据');
            exit;
        }
    }


    public function orders_delAction()
    {
        $page = (!empty($this->params['page'])) ? (int)$this->params['page'] : 1;
        $source = (!empty($this->params['_source'])) ? $this->params['_source'] : '';                           # 订单来源
        $shop_no = (!empty($this->params['_shop_no'])) ? (int)$this->params['_shop_no'] : '';                  # 配送门店
        $company_no = (!empty($this->params['_company_no'])) ? (int)$this->params['_company_no'] : '';         # 分司
        $_ph_no = (!empty($this->params['_ph_no'])) ? $this->params['_ph_no'] : '';                            # 配货号
        $_order_no = (!empty($this->params['_order_no'])) ? $this->params['_order_no'] : '';                    # 订单号

        $startdate = (!empty($this->params['startdate'])) ? $this->params['startdate'] : '';                          # 下单开始
        $enddate = (!empty($this->params['enddate'])) ? $this->params['enddate'] : '';                          # 下单结束
        $startdate1 = $startdate;
        $enddate1 = $enddate;
        $number_page = (!empty($this->params['number_page'])) ? $this->params['number_page'] : Data::$_number_page;

        $sourceS = explode('-', $source);
        $sourceN = $sourceS[0];
        $sourceK = $sourceS[1];


        $store =  $this->GetStores([]);
        $CompanyLiists =  $this->GetCompanys([]);
        $sourceLists =  $this->GetSources([]);

        //抓列表
        $where_fields = 'o.isdeleted = 1 and o.status = 100 ';
        if (!empty($shop_no)) {
            $where_fields .= ' AND o.shop_no=' . $shop_no . '';
        }

        if (!empty($_ph_no)) {
            $where_fields .= " AND o.ph_no='$_ph_no'";
        }
        if (!empty($_order_no)) {
            $where_fields .= " AND o.order_no='$_order_no'";
        }
        if (!empty($source)) {
            $where_fields .= " AND o.source = '$sourceN'";
        }
        if (!empty($company_no)) {
            $where = array("AND" => array("=" => array('company_id' => $company_no,'isdeleted' => 0)));
            $field = 'id,store_id,storename';
            $_store_list = $this->model->getAll($where, 'xd_store', '', $field);
            $_q_stores=array();
            if(!empty($_store_list)){
                foreach($_store_list as $value){
                    $_q_stores[]=" o.shop_no='".$value['store_id']."' ";
                }
                $where_fields .= " AND (".join(" OR ",$_q_stores) .")";
            }else{
                $where_fields .= " AND o.shop_no='".$company_no."' ";   //没有门店，SQL执行后空值
            }
        }

        $left = "left join orders_express as d ON o.ph_no = d.ph_no and o.status = d.status";
        $sql = "SELECT o.*,d.express_fee ,d.express_order_no,d.shop_express_no FROM orders as o $left  WHERE $where_fields  ORDER BY o.id DESC ";

//         echo $sql;
        $total_count = $this->model->getTotalCountByJoin($sql);
        $res = $this->model->getJoinByPageR($page, $number_page, $sql);
        $rsp_page_list = Tools::getPagesPost($_SERVER["REQUEST_URI"], $number_page, $page, $total_count);
        if (!empty($res)) {
            while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                $company_id = $store['store_data'][$row['shop_no']]['company_id'];
                $row['name'] = $CompanyLiists[$company_id];
                $rsp_list[] = $row;
            }
        }

//        echo '<pre>';
//        var_dump($rsp_list);

        $this->view->setVariable("_company_no", $company_no);
        $this->view->setVariable("_source", $sourceK);
        $this->view->setVariable("sourceN", $sourceN);
        $this->view->setVariable("_shop_no", $shop_no);
        $this->view->setVariable("_ph_no", $_ph_no);
        $this->view->setVariable("_order_no", $_order_no);
        $this->view->setVariable("startdate", $startdate1);
        $this->view->setVariable("enddate", $enddate1);
        $this->view->setVariable("CompanyLiists", $CompanyLiists);
        $this->view->setVariable("sourceLists", $sourceLists);
        $this->view->setVariable("storeLiists", $store['storeLiists']);
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("rsp_page_list", $rsp_page_list);
        $this->view->setVariable("total_count", $total_count);
        $this->view->setVariable("page", $page);
        $this->view->setVariable("number_page", $number_page);
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/order/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


}
